package com.yunbiao.ybbusstopplate.utils.core;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;


import com.blankj.utilcode.util.ActivityUtils;
import com.yunbiao.ybbusstopplate.base.APP;
import com.yunbiao.ybbusstopplate.base.HeartBeatClient;
import com.yunbiao.ybbusstopplate.utils.CommonUtils;
import com.yunbiao.ybbusstopplate.utils.ThreadUitls;
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache;
import com.yunbiao.ybbusstopplate.utils.core.power.PowerOffTool;
import com.yunbiao.ybbusstopplate.utils.net.ResourceUpdate;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class TYTool {
    private static final String TAG = "TYTool";
    private static final ResourceUpdate resourceUpdate = new ResourceUpdate();
    public static void init(){

    }

    public static void showTitleTip(String title) {
//        TextView textView = new TextView(HeartBeatClient.getInstance().getMainActivity());
        Log.d(TAG, "showTitleTip: title-->"+title);
        TextView textView = new TextView(APP.Companion.getAppContext());
        textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        textView.setBackgroundColor(Color.WHITE);
        textView.setTextColor(Color.BLACK);
        textView.setTextSize(40);
        textView.setText(title);

//        Toast toast = new Toast(HeartBeatClient.getInstance().getMainActivity());
        Toast toast = new Toast(APP.Companion.getAppContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setView(textView);
        toast.show();
    }

    public static final String[] extsds = new String[]{"extsd", "external_sd", "usb_storage/USB_DISK1/udisk0",
            "usb_storage/USB_DISK0/udisk0", "usb_storage/USB_DISK2/udisk0", "usb_storage/USB_DISK2",
            "usbhost", "usbhost0", "usbhost1", "usbhost2", "usbhost3", "sda1", "usb_storage",
            "media_rw/usbotg-sda", "media_rw/usbotg-sda0", "media_rw/usbotg-sda1", "media_rw/usbotg-sda2", "mmcblk1p1"};
    public static List<String> extsdList=new ArrayList<>();
    public static String getSdcardPath() {
        String uPath="";
        for (String path : extsdList) {
            File file =null;
            if (path.startsWith("/")){
                file=new File(path.substring(1));
            }else {
                file=new File("mnt/" + path);
            }
            if (file!=null&&file.exists()) {
                if (file.canExecute() && file.canWrite() && file.canRead()) {
                    uPath=file.getPath();
                    break;
                }
            }
        }
        //本地目录
        if (TextUtils.isEmpty(uPath)){
            uPath="mnt/sdcard";
        }
//        Log.d(TAG, "getSdcardPath: path-->"+uPath);
        return uPath;
    }
    /**
     * 获取json 值
     *
     * @param jsonObj jsonObejct
     * @param param   需要获取的参数
     * @param defVal  缺省值
     * @return Object
     */
    public static Object getJsonObj(JSONObject jsonObj, String param, Object defVal) {
        Object objValue;
        try {
            objValue = jsonObj.get(param);
            if (objValue == null && defVal != null) {
                objValue = defVal;
            }
            if (objValue instanceof String) {
                if (TextUtils.isEmpty((String) objValue)) {
                    objValue = defVal;
                }
            }
        } catch (JSONException e) {
            objValue = defVal;
        }
        return objValue;
    }


    //后台远程更新布局之前，更改tag和释放一些资源
    public static void releaseAllView() {
        LayoutCache.putLayoutPosition("0");//更改是服务器布局还是离线布局
//        MyXWalkView.onDestory();
//        MyWebView.onDestory();
    }

    public static void downloadResource() {
        resourceUpdate.getDeviceResource(HeartBeatClient.getDeviceNo());
    }

    public static boolean boardIsXBH() {//判断板子是不是小百合的，返回true
        Integer broadInfo = CommonUtils.getBroadType();
        return broadInfo == 4;
    }

    public static boolean boardIsJYD() {//判断板子是不是建益达的，返回true
        Integer broadInfo = CommonUtils.getBroadType();
        return broadInfo == 5;
    }
    public static boolean boardIsQingJi(){//判断主板是否为庆吉
        Integer broadType = CommonUtils.getBroadType();
        return broadType==6;
    }

    public static boolean boardIsYiSheng_M11(){//判断主板是否为亿晟
        Integer broadType = CommonUtils.getBroadType();
        return broadType==31;
    }

    public static boolean boardIsYiSheng(){//判断主板是否为亿晟
        Integer broadType = CommonUtils.getBroadType();
        return broadType==3||broadType==31;
    }

    public static boolean boardIsSLX560(){//判断主板是否为9施乐讯560
        Integer broadType = CommonUtils.getBroadType();
        return broadType==9;
    }

    public static void sendBroadcast(String action) {
        Intent intent = new Intent();
        //设置Intent的Action属性
        intent.setAction(action);
        //如果只传一个bundle的信息，可以不包bundle，直接放在intent里
        //发送广播
      APP.Companion.getAppContext().sendBroadcast(intent);
    }

    // CoreInfoHandler 关机重启三秒等待
    public static ProgressDialog coreInfoShow3sDialog(String title,String message) {
        Activity activity= ActivityUtils.getTopActivity();

        ProgressDialog pd=null;
        if (activity==null){
            showTitleTip(message);
            return null;
        }else {
            pd=new ProgressDialog(activity);
        }
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setTitle(title);
        pd.setMessage(message);
        pd.setIndeterminate(false);
        pd.setCancelable(true); // 设置ProgressDialog 是否可以按退回键取消
        return pd;
    }

    public static ProgressDialog pd;
    /**
     * 软件升级
     */
    public static void updatePd() {
        Activity activity = ActivityUtils.getTopActivity();
        pd = new ProgressDialog(activity);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setTitle("通知");
        pd.setMessage("正在安装相关应用，请耐心等待！");
        pd.show();
    }

    public static CountDownTimer powerShutDown = new CountDownTimer(3 * 1000, 1000) {//3秒
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            // 关机
            PowerOffTool.getPowerOffTool().powerShutdown();
        }
    };

    //重启软件
    public static CountDownTimer AppRestart = new CountDownTimer(3 * 1000, 1000) {//3秒
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            CommonUtils.reLoadApp();
        }
    };

    public static CountDownTimer restart = new CountDownTimer(3 * 1000, 1000) {//3秒
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            // 重启
            PowerOffTool.getPowerOffTool().restart();
        }
    };

    public static String getSDDiskCon() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            double blockSize = sf.getBlockSize();
            double blockCount = sf.getBlockCount();
            double availCount = sf.getAvailableBlocks();

            Double level = (availCount * blockSize / 1024);
            Double all = (blockSize * blockCount / 1024);

            Double use = all - level;

            Double useDou = use / 1024 / 1024;
//            Double levelDou = level / 1024 / 1024;
            Double allDou = all / 1024 / 1024;

            BigDecimal useB = new BigDecimal(useDou);
            double useF = useB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

//            BigDecimal levelB = new BigDecimal(levelDou);
//            double levelF = levelB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            BigDecimal allB = new BigDecimal(allDou);
            double allF = allB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            String useStr = useF + "G";
            if (useF < 1) {
                useF = useF * 1024;
                useStr = useF + "M";
            }
//            String levelStr = levelF + "G";
//            if (levelF < 1) {
//                levelF = levelF * 1024;
//                levelStr = levelF + "M";
//            }
            String allStr = allF + "G";
            if (allF < 1) {
                allF = allF * 1024;
                allStr = allF + "M";
            }
            return "已用:" + (useStr) + "/可用:" + allStr;
        } else {
            return "";
        }
    }

    public static void downloadLocalLayoutResource() {
        ThreadUitls.runInThread(new Runnable() {
            @Override
            public void run() {
                // 中部
                String layoutStr = LayoutCache.getLayoutCacheAsString();
                resourceUpdate.downloadLocalLayoutResource(layoutStr);

                // 底部
                String layoutStrBottom = LayoutCache.getLayoutCacheAsStringBottom();
                resourceUpdate.downloadLocalLayoutResourceBottom(layoutStrBottom);
            }
        });
    }

    /**
     * 给参数返回指定小数点后几位的四舍五入
     *
     * @param sourceData 传入的要舍取的元数据
     * @param sf         取舍的格式（主要用到"#.0"的格式，此为小数点后1位；"#.00"为小数点后2位，以此类推）
     * @return 舍取后的 数据
     */
    public static Integer getFloatToInt(Float sourceData, String sf) {
        DecimalFormat df = new DecimalFormat(sf);
        String str = df.format(sourceData);
        return Integer.parseInt(str);
    }
}